package com.chentf.creational.serializable.code;

import java.io.*;
import java.text.MessageFormat;

/**
 * 测试对象的序列化和反序列
 */
public class TestObjSerializeAndDeserialize {
    //序列化Person成功后在D盘生成了一个Person.txt文件，而反序列化Person是读取D盘的Person.txt后生成了一个Person对象
    public static void main(String[] args) throws IOException, ClassNotFoundException {
        serializePerson(); //序列化
        System.out.println("-------分隔符-------");
        Person p = DeserializePerson();//反序列Perons对象
        System.out.println(MessageFormat.format("name={0},age={1},sex={2}",p.getName(), p.getAge(), p.getSex()));
    }

    //序列化Person对象
    public static void serializePerson() throws IOException {
        Person person = new Person();
        person.setName("chentf");
        person.setAge(31);
        person.setSex("男");
        // ObjectOutputStream 对象输出流，将Person对象存储到D盘的Person.txt文件中，完成对Person对象的序列化操作
        ObjectOutputStream objectOutputStream = new ObjectOutputStream(new FileOutputStream(new File("D:\\person.txt")));
        objectOutputStream.writeObject(person);
        System.out.println("Person对象序列化成功！");
        objectOutputStream.close();
    }

    //反序列Perons对象
    private static Person DeserializePerson() throws IOException, ClassNotFoundException {
        ObjectInputStream objectInputStream = new ObjectInputStream(new FileInputStream(new File("D:\\person.txt")));
        Person person = (Person) objectInputStream.readObject();
        System.out.println("Person对象反序列化成功！");
        objectInputStream.close();
        return person;
    }

}
